package com.jinkeen.xiaxie.customView

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Typeface
import android.inputmethodservice.Keyboard
import android.inputmethodservice.KeyboardView
import android.util.AttributeSet
import android.view.View
import com.jinkeen.xiaxie.R

/**
 * @description: TODO
 * @author whz
 * @date 2022-06-15 14:48
 * @version 1.0
 */

class KeyBoardDemo : KeyboardView {

    constructor(context: Context, attrs: AttributeSet) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    @SuppressLint("UseCompatLoadingForDrawables")
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        val keyboard = keyboard
        keyboard?.let {
            val keys = keyboard.keys
            if (keys != null && keys.size > 0) {
                val paint = Paint()
                paint.textAlign = Paint.Align.CENTER
                val font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD)
                paint.typeface = font
                paint.isAntiAlias = true
                for (i in keys.indices) {
                    if (keys[i].codes[0] == -4) {
                        val dr = context.resources.getDrawable(R.drawable.icon_me)
                        dr.setBounds(
                            keys[i].x,
                            keys[i].y,
                            keys[i].x + keys[i].width,
                            keys[i].y + keys[i].height
                        )
                        dr.draw(canvas!!)
                        keys[i].label?.let {
                            paint.textSize = dp2Px(18) as Float
                            //设置字体颜色
                            paint.color = context.resources.getColor(R.color.white)
                        }
                    }
                }
            }
        }
    }

    private fun dp2Px(dp: Int) = (resources.displayMetrics.density * dp + 0.5f).toInt()

}